package com.xs.letcode;

/**
 * @author xs
 * date 2018/9/11 13:55
 */
public class BinaryAdd {

	/**
	 * @param a 1100
	 * @param b 101
	 */
	public static String add(String a, String b) {

		b = addZeroForNum(b, a.length());
		//忽略a,b 参数检查 (A>B)
		char[] charsA = a.toCharArray();
		char[] charsB = b.toCharArray();

		//结果数组
		char[] result = new char[charsA.length + 1];
		int carryFlag = 0; //上一位是否进位
		for (int i = charsA.length - 1; i >= 0; i--) {
			char x = charsA[i];
			char y = charsB[i];
			int eachTotal = sum(x, y, carryFlag);
			if (eachTotal == 0) {
				result[i+1]='0';
				carryFlag=0;
			} else if (eachTotal == 1) {
				result[i+1]='1';
				carryFlag=0;
			} else if (eachTotal == 2) {
				result[i+1]='0';
				carryFlag=1;
			} else if (eachTotal == 3) {
				result[i+1]='1';
				carryFlag=1;
			}
			if(i==0&&carryFlag==1){
				result[0]='1';
			}
		}

		return new String(result);
	}

	public static int sum(char x, char y, int carryFlag) {
		int sum = (x - '0') + (y - '0') + carryFlag;
		return sum;
	}


	public static String addZeroForNum(String str, int strLength) {
		int strLen = str.length();
		if (strLen < strLength) {
			while (strLen < strLength) {
				StringBuffer sb = new StringBuffer();
				sb.append("0").append(str);// 左补0
				// sb.append(str).append("0");//右补0
				str = sb.toString();
				strLen = str.length();
			}
		}
		return str;
	}

	public static void main(String[] args) {
		String a = "11001";
		String b = "10000";
		//System.out.println(addZeroForNum(b,a.length()));

		System.out.println(add(a, b));
	}

}
